<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/html" xmlns="http://www.w3.org/1999/html">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>SoundJS Tutorial: Basics and Best Practices</title>
    <link href="../_shared/tutorial.css" rel="stylesheet" type="text/css">
    <script src="../_shared/tutorial.js"></script>

    <!-- SyntaxHighlighter-->
    <script src="../_shared/SyntaxHighlighter/shCore.js"></script>
    <script src="../_shared/SyntaxHighlighter/shBrushJScript.js"></script>
    <script src="../_shared/SyntaxHighlighter/shBrushXml.js"></script>
    <link href="../_shared/SyntaxHighlighter/shCore.css" rel="stylesheet" type="text/css">
    <link href="../_shared/SyntaxHighlighter/shThemeCreateJS.css" rel="stylesheet" type="text/css">
</head>

<body onLoad="initTutorial();">
<article>
<header>
    <h1>SoundJS: Basics and Best Practices</h1>

    <p>
        <strong>Synopsis:</strong> Play audio with best practices.<br>
        <strong>Topics:</strong> sound, play, best practices, basics<br>
        <strong>Target:</strong> SoundJS 0.5.2+
    </p>
</header>
<p class="highlight">
	This tutorial is part of the <a href="https://github.com/CreateJS/SoundJS/" target="_blank">SoundJS GitHub repository</a>.<br />
	Check out the repository for more tutorials and a handful of helpful samples.
</p>

<section>
    <header>
        <h2>Intro</h2>
    </header>
    <p>SoundJS is a JavaScript library that provides a simple API for playing sounds in a consistent cross-browser
        supported way. Sounds great doesn't it? But how do you actually make it work? And what are some good approaches
        to take? We explore these questions in this tutorial.
    </p>

    <p>
        After reading this article, you should be able to play audio on a website on any desktop browser that
        supports audio in some form, using a single, easily maintained code base. The end result will be very similar to
        the <a href="https://github.com/CreateJS/SoundJS/blob/master/examples/JustPlay.html" target="_blank">"JustPlay"
        example</a> in the <a href="https://github.com/CreateJS/SoundJS/" target="_blank">SoundJS GitHub repository</a>.
    </p>

</section>

<section>
    <header>
        <h2>Basics</h2>
    </header>
    <p>
        This tutorial assumes that you already have a basic grasp of html and javascript. We'll start with some best
        practices.</p>

    <p>
        In all of our <a href="https://github.com/CreateJS/SoundJS/tree/master/examples" target="_blank">SoundJS
        examples</a> you'll see that CSS is always loaded in the &lt;HEAD&gt;. This is so the page styles are loaded
        before the body content that is displayed to the user, so they never see un-styled content.</p>

    <p>
        Conversely, all of our scripts are loaded at the bottom of the &lt;BODY&gt;. This is because JavaScript has a
        blocking behavior, preventing the display of any content following it until the script load has completed.
        Generally it is better to show a user something, then add functionality using JavaScript, rather then to make the user
        wait for everything to load first.
    </p>

</section>

<section>
    <header>
        <h2>Initial Setup</h2>
    </header>
    <p>
        After creating a new html document, the first thing we'll need to play audio is, not surprisingly, a link to the
        SoundJS library. SoundJS is hosted on a <a href="http://code.createjs.com/" target=_blank>CDN</a>, so in the
        HTML body we create a &lt;SCRIPT&gt; tag and set it's source to <code>http://code.createjs.com/soundjs-0.5.2.min.js</code>.
        Note that the SoundJS library is available globally under the "createjs" namespace. For example the primary
        class "Sound" is accessed in code with <code>createjs.Sound</code>.
    </p>
    <textarea class="brush: js;" readonly>
        &lt;script src="http://code.createjs.com/soundjs-0.5.2.min.js"&gt;&lt;/script&gt;
    </textarea>

    <p>
        Next, create an inline script that does the actual work of playing the sound. In general, it is a better
        practice to create an external JavaScript file and load it in the html. This gives the benefit of separating
        code into more maintainable chunks and allows browsers to cache the files for quicker loads if users revisit
        your site or visit different areas in your site that use the same script. However, for our purposes, it is easier
        to demonstrate how to play sound inline in the HTML file.</p>

    <p>Inside this script, create an <code>init</code> function, which will be called by adding an onload handler to the
        &lt;BODY&gt; tag. The <code>onload</code> callback will execute the <code>init</code> function when everything
        on the page has loaded. The body tag should look similar to the following:
    </p>
    <textarea class="brush: js;" readonly>
        &lt;body onload="init()"&gt;
        &lt;script src="http://code.createjs.com/soundjs-0.5.2.min.js"/&gt;
        &lt;script&gt;
        function init() {

        }
        &lt;/script&gt;
        &lt;/body&gt;
    </textarea>

</section>

<section>
    <header>
        <h2>Plugins</h2>
    </header>
    <p>
        Once setup is complete, we can get directly to loading and playing sounds. It is important to know, however,
        that SoundJS uses a number of plugins to enable audio playback in different browsers. There are no additional
		steps to initialize the plugins, and the default plugin set (Web Audio and HTML Elements) will work in the
		majority of modern browsers. For this tutorial, the default plugin set will be fine.
    </p>
    <p>
        Plugin selection will happen automatically the first time audio is preloaded or played, however if you need to
        determine if audio will play <em>before</em> that (to show a message for example), a handy method exists to
        manually initialize the default plugins: <a href="http://www.createjs.com/Docs/SoundJS/classes/Sound.html#method_initializeDefaultPlugins" target="_blank">
        <code>initializeDefaultPlugins()</code></a> can be called at any time.
    </p>
    <textarea class="brush: js;" readonly>
        // if initializeDefaultPlugins returns false, we cannot play sound in this browser
        if (!createjs.Sound.initializeDefaultPlugins()) { return; }
    </textarea>
</section>

<section>
    <header>
        <h2>Internal Preloading</h2>
    </header>
    <p>
        It is a best practice to preload audio so it is ready for immediate playback. We have an <a href="../SoundJS%20and%20PreloadJS/index.html" target="_blank">
        excellent tutorial on preloading techniques</a>, but for this example we'll only be using a basic internal
        preloading approach.
    </p>
    <p>
        SoundJS accepts an array of objects that represent each audio instance, containing a <code>src</code>
        property that is the URI of the audio file. These objects can have other properties, and we use an
        <code>id</code> property as a best practice, as it can make future interactions easier.
    </p>
    <p>
        We store the relative path to our audio assets as a variable as a best practice, which allows us to make a
        single change when moving the files, rather than trying to track down every individual use. Another best
        practice is to include both an mp3 and ogg version of your audio to give the broadest playback support possible.
        SoundJS enables you to do this by adding a setting the
		<a href="http://www.createjs.com/Docs/SoundJS/classes/Sound.html#property_alternateExtensions" target="_blank">
		alternateExtensions property</a>. The code will look like this:
    </p>
    <textarea class="brush: js;" readonly>
        var audioPath = "assets/";
        var sounds = [
        	{id:"Music", src:"M-GameBG.ogg"},
        	{id:"Thunder", src:"Thunder1.ogg"}
        ];
		createjs.Sound.alternateExtensions = ["mp3"];
    </textarea>

    <p>
        With our audio comfortably defined in a, let's move on to loading the audio. SoundJS uses an
        Event model, so we can add an event listener for the <a href="http://www.createjs.com/Docs/SoundJS/classes/Sound.html#event_fileload" target="_blank">
        <code>fileload</code> event</a>. It is a best practice to add this <em>before</em> we begin loading the audio to avoid a race
        condition where audio can load from cache immediately. The second parameter of the listener is the function to
        call back. Once this is ready, the audio load can be kicked off using the <a href="http://www.createjs.com/Docs/SoundJS/classes/Sound.html#method_registerSounds" target="_blank">
        <code>registerSounds</code> method</a>. Our deceptively simple and clean code should look like this:
    </p>
    <textarea class="brush: js;" readonly>
        function init() {
        	// create an array and audioPath (above)
        	createjs.Sound.addEventListener("fileload", handleLoad);
        	createjs.Sound.registerSounds(sounds, audioPath);
        }

        function handleLoad(event) {
        	// Do something with the loaded sound
        }
    </textarea>

</section>

<section>
    <header>
        <h2>Playback</h2>
    </header>
    <p>
        Once audio has been registered (via loading), it can be played anywhere with the super simple
        <a href="http://www.createjs.com/Docs/SoundJS/classes/Sound.html#method_play" target="_blank"><code>play()</code>
        method</a>. It's worth noting that the <code>handleLoad</code> call in the previous example will fire once for
        each sound we load. This example shows how to immediately play audio once it is internally preloaded:
    </p>
    <textarea class="brush: js;" readonly>
        function handleLoad(event) {
        	createjs.Sound.play(event.src);
        }
    </textarea>

    <p>
        This is it, the last step when we finally make some noise! Open up the html file in a web browser, or using
        your favorite localhost tool. Hear the awesome? Great job! This is what the final code should look like:
    </p>
    <textarea class="brush: js;" readonly>
        &lt;body onload="init()"&gt;
        &lt;script src="http://code.createjs.com/soundjs-0.5.2.min.js"/&gt;
        &lt;script&gt;
        function init() {
        	// if initializeDefaultPlugins returns false, we cannot play sound in this browser
			if (!createjs.Sound.initializeDefaultPlugins()) {return;}

			var audioPath = "assets/";
			var sounds = [
				{id:"Music", src:"18-machinae_supremacy-lord_krutors_dominion.ogg"},
				{id:"Thunder", src:"Thunder1.ogg"}
			];

			createjs.Sound.alternateExtensions = ["mp3"];
			createjs.Sound.addEventListener("fileload", handleLoad);
			createjs.Sound.registerSounds(sounds, audioPath);
        }

        function handleLoad(event) {
        	createjs.Sound.play(event.src);
        }
        &lt;/script&gt;
        &lt;/body&gt;
    </textarea>

    <p>Check out sample.html provided in this tutorial's directory.</p>
</section>

<section>
    <header>
        <h2>Conclusion</h2>
    </header>

    <p>
        This wraps up the tutorial on basics and best practices, which should give you a great start. The above example
        will not work on all mobile devices (phones and tablets), due to security requirements that require user input to
        play audio. This topic is the focus of the <a href="../Mobile%20Safe%20Approach/index.html" target="_blank">
        Mobile Safe tutorial</a>. Good places to learn more are SoundJS are the
        <a href="http://createjs.com/Docs/SoundJS" target="_blank">online documentation</a>
        and <a href="https://github.com/CreateJS/SoundJS/tree/master/examples" target="_blank">examples in GitHub</a>.
    </p>
    <p>
        Hope that helps!
    </p>
</section>

<section>
    <header>
        <h2>Related Links</h2>
    </header>
    <ol>
        <li>Download CreateJS from the <a href="http://code.createjs.com" target="_blank">Adobe CDN</a>.</li>
        <li>Get the latest SoundJS source code, including minified versions of SoundJS and FlashAudioPlugin from <a
                href="http://github.com/CreateJS/SoundJS/" target="_blank">GitHub</a>.
        </li>
        <li>Read more about SoundJS in the <a href="http://createjs.com/Docs/SoundJS" target="_blank">online
            docs</a> (also available in GitHub).
        </li>
        <li>Get involved in active <a href="http://community.createjs.com/discussions/soundjs" target="_blank">community
            discussion</a>.
        </li>
    </ol>
</section>

</article>
</body>
</html>
